<template>
  <div class="brand-management">
    <div class="header">
      <h2>品牌管理</h2>
      <button @click="showAddDialog = true" class="btn btn-primary">
        <i class="fas fa-plus"></i> 新增品牌
      </button>
    </div>

    <!-- 搜索过滤区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>关键词搜索:</label>
          <input
            v-model="searchParams.keyword"
            type="text"
            placeholder="品牌名称或标识"
            class="form-input"
            @keyup.enter="loadBrandList"
          />
        </div>
        <div class="filter-item">
          <label>状态:</label>
          <select v-model="searchParams.status" class="form-select">
            <option value="">全部状态</option>
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </div>
        <div class="filter-actions">
          <button @click="loadBrandList" class="btn btn-info">
            <i class="fas fa-search"></i> 搜索
          </button>
          <button @click="resetSearch" class="btn btn-secondary">
            <i class="fas fa-redo"></i> 重置
          </button>
        </div>
      </div>
    </div>

    <!-- 品牌列表表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>品牌名称</th>
            <th>标识(Slug)</th>
            <th>Logo</th>
            <th>国家/地区</th>
            <th>状态</th>
            <th>排序</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="brand in brandList" :key="brand.id">
            <td>{{ brand.id }}</td>
            <td class="brand-name">
              <div class="brand-info">
                <strong>{{ brand.name }}</strong>
                <p v-if="brand.description" class="brand-desc">{{ brand.description }}</p>
              </div>
            </td>
            <td>{{ brand.slug }}</td>
            <td class="brand-logo">
              <img v-if="brand.logoUrl" :src="brand.logoUrl" :alt="brand.name" class="logo-image" />
              <span v-else class="no-logo">无Logo</span>
            </td>
            <td>{{ brand.country || '-' }}</td>
            <td>
              <span :class="['status-badge', brand.status === 1 ? 'status-active' : 'status-inactive']">
                {{ brand.status === 1 ? '启用' : '禁用' }}
              </span>
            </td>
            <td>{{ brand.sortOrder }}</td>
            <td>{{ formatDateTime(brand.createdAt) }}</td>
            <td class="actions">
              <button @click="editBrand(brand)" class="btn btn-sm btn-warning">
                <i class="fas fa-edit"></i> 编辑
              </button>
                             <button @click="deleteBrandAction(brand)" class="btn btn-sm btn-danger">
                 <i class="fas fa-trash"></i> 删除
               </button>
            </td>
          </tr>
          <tr v-if="brandList.length === 0">
            <td colspan="9" class="no-data">暂无品牌数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共 {{ total }} 条记录，第 {{ current }} / {{ pages }} 页
      </div>
      <div class="pagination-controls">
        <button
          @click="changePage(current - 1)"
          :disabled="current <= 1"
          class="btn btn-sm btn-secondary"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button
            v-for="page in getPageNumbers()"
            :key="page"
            @click="changePage(page)"
            :class="['btn', 'btn-sm', page === current ? 'btn-primary' : 'btn-outline']"
          >
            {{ page }}
          </button>
        </span>
        <button
          @click="changePage(current + 1)"
          :disabled="current >= pages"
          class="btn btn-sm btn-secondary"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑品牌弹窗 -->
    <div v-if="showAddDialog || showEditDialog" class="modal-overlay">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditDialog ? '编辑品牌' : '新增品牌' }}</h3>
          <button @click="closeDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveBrand">
            <div class="form-group">
              <label>品牌名称 *</label>
              <input v-model="formData.name" type="text" required class="form-input" placeholder="请输入品牌名称" />
            </div>
            <div class="form-group">
              <label>标识(Slug)</label>
              <input v-model="formData.slug" type="text" class="form-input" placeholder="留空自动生成" />
            </div>
            <div class="form-group">
              <label>Logo URL</label>
              <input v-model="formData.logoUrl" type="url" class="form-input" placeholder="请输入Logo图片链接" />
            </div>
            <div class="form-group">
              <label>国家/地区</label>
              <input v-model="formData.country" type="text" class="form-input" placeholder="请输入国家或地区" />
            </div>
            <div class="form-group">
              <label>品牌描述</label>
              <textarea v-model="formData.description" class="form-textarea" rows="3" placeholder="请输入品牌描述"></textarea>
            </div>
            <div class="form-group">
              <label>排序值 *</label>
              <input v-model.number="formData.sortOrder" type="number" required class="form-input" placeholder="数字越小排序越靠前" />
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model.number="formData.status" class="form-select">
                <option :value="1">启用</option>
                <option :value="0">禁用</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeDialog" class="btn btn-secondary">取消</button>
              <button type="submit" :disabled="saving" class="btn btn-primary">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getBrandList, createBrand, updateBrand, deleteBrand } from '@/api/brand'
import type { Brand, BrandQueryParams, BrandCreateRequest, BrandUpdateRequest } from '@/types/brand'

// 响应式数据
const brandList = ref<Brand[]>([])
const total = ref(0)
const current = ref(1)
const pages = ref(0)
const loading = ref(false)
const saving = ref(false)

// 弹窗状态
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const currentBrand = ref<Brand | null>(null)

// 搜索参数
const searchParams = reactive<BrandQueryParams>({
  keyword: '',
  status: undefined,
  page: 1,
  size: 10
})

// 表单数据
const formData = reactive({
  id: 0,
  name: '',
  slug: '',
  logoUrl: '',
  country: '',
  description: '',
  sortOrder: 1,
  status: 1
})

// 加载品牌列表
const loadBrandList = async () => {
  loading.value = true
  try {
    searchParams.page = current.value
    const response = await getBrandList(searchParams)
    brandList.value = response.data.records
    total.value = response.data.total
    pages.value = response.data.pages
    current.value = response.data.current
  } catch (error) {
    console.error('加载品牌列表失败:', error)
    alert('加载品牌列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  searchParams.status = undefined
  current.value = 1
  loadBrandList()
}

// 分页切换
const changePage = (page: number) => {
  if (page < 1 || page > pages.value) return
  current.value = page
  loadBrandList()
}

// 获取分页数字
const getPageNumbers = () => {
  const nums: number[] = []
  const start = Math.max(1, current.value - 2)
  const end = Math.min(pages.value, current.value + 2)
  
  for (let i = start; i <= end; i++) {
    nums.push(i)
  }
  return nums
}

// 编辑品牌
const editBrand = (brand: Brand) => {
  currentBrand.value = brand
  Object.assign(formData, {
    id: brand.id,
    name: brand.name,
    slug: brand.slug,
    logoUrl: brand.logoUrl || '',
    country: brand.country || '',
    description: brand.description || '',
    sortOrder: brand.sortOrder,
    status: brand.status
  })
  showEditDialog.value = true
}

// 删除品牌
const deleteBrandAction = async (brand: Brand) => {
  if (!confirm(`确定要删除品牌"${brand.name}"吗？`)) return
  
  try {
    await deleteBrand(brand.id)
    alert('删除成功')
    loadBrandList()
  } catch (error) {
    console.error('删除品牌失败:', error)
    alert('删除品牌失败')
  }
}

// 保存品牌
const saveBrand = async () => {
  saving.value = true
  try {
    if (showEditDialog.value && currentBrand.value) {
      const updateData: BrandUpdateRequest = {
        name: formData.name,
        slug: formData.slug,
        logoUrl: formData.logoUrl,
        country: formData.country,
        description: formData.description,
        sortOrder: formData.sortOrder,
        status: formData.status
      }
      await updateBrand(currentBrand.value.id, updateData)
      alert('更新成功')
    } else {
      const createData: BrandCreateRequest = {
        name: formData.name,
        slug: formData.slug,
        logoUrl: formData.logoUrl,
        country: formData.country,
        description: formData.description,
        sortOrder: formData.sortOrder,
        status: formData.status
      }
      await createBrand(createData)
      alert('创建成功')
    }
    
    closeDialog()
    loadBrandList()
  } catch (error) {
    console.error('保存品牌失败:', error)
    alert('保存品牌失败')
  } finally {
    saving.value = false
  }
}

// 关闭弹窗
const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  currentBrand.value = null
  Object.assign(formData, {
    id: 0,
    name: '',
    slug: '',
    logoUrl: '',
    country: '',
    description: '',
    sortOrder: 1,
    status: 1
  })
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadBrandList()
})
</script>

<style scoped>
.brand-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.filter-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filter-item label {
  font-weight: 500;
  color: #555;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.form-input, .form-select, .form-textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus, .form-select:focus, .form-textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,.25);
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

.data-table td {
  padding: 12px;
  border-bottom: 1px solid #dee2e6;
}

.brand-name .brand-info strong {
  display: block;
  color: #333;
}

.brand-name .brand-desc {
  margin: 4px 0 0;
  color: #666;
  font-size: 12px;
}

.brand-logo .logo-image {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border-radius: 4px;
}

.brand-logo .no-logo {
  color: #999;
  font-style: italic;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background: #d4edda;
  color: #155724;
}

.status-inactive {
  background: #f8d7da;
  color: #721c24;
}

.actions {
  white-space: nowrap;
}

.actions .btn {
  margin-right: 8px;
}

.no-data {
  text-align: center;
  color: #666;
  font-style: italic;
  padding: 40px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-info {
  color: #666;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-outline {
  background: transparent;
  border: 1px solid #ddd;
  color: #333;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.modal-content {
  background: #ffffff;
  border-radius: 4px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999999;
  padding: 4px;
  line-height: 1;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #666666;
}

.modal-body {
  padding: 20px;
  background: #ffffff;
}

.form-group {
  margin-bottom: 18px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 400;
  color: #666666;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style> 